package com.upup.cloud.insert;

import com.google.gson.internal.LinkedTreeMap;
import com.upup.cloud.insert.entity.Qnracess;
import com.upup.cloud.insert.service.QnracessRepositoryService;
import com.upup.cloud.insert.service.RedisService;
import com.upup.cloud.insert.utils.MD5Utils;
import com.upup.cloud.insert.utils.StrUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.WebApplicationType;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Map;

@Slf4j
@SpringBootApplication
public class InsertApplication implements CommandLineRunner {

    @Resource(name = "redisServiceImpl")
    RedisService redisService;
    @Resource(name = "redisServiceImpl2")
    RedisService redisService2;
    @Autowired
    QnracessRepositoryService qnracessRepositoryService;
    public static void main(String[] args) {
        new SpringApplicationBuilder(InsertApplication.class)
                .web(WebApplicationType.NONE)
                .run(args);
    }

    @Override
    public void run(String... args) throws Exception {
//        qnracessRepositoryService.save(new Qnracess());
        for (int i = 0; i < 1; i++) {
            new Thread("xc") {
                @Override
                public void run() {
                    DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                    while (true) {
                        try {
                            List<Qnracess> lists = new ArrayList<>();

                            String str = redisService.rpop("chhk_data");
                            if (StringUtils.isEmpty(str)) {
                                Thread.sleep(1000);
                                continue;
                            }
                            Map<String, List<LinkedTreeMap>> map = (Map) StrUtils.jsonTobean(str, Map.class);

                            for (Map.Entry<String, List<LinkedTreeMap>> entry : map.entrySet()) {
                                //获取原有的航班
                                String string = redisService2.get(entry.getKey());
                                if (StringUtils.isEmpty(string)) {
                                    List<Qnracess> list = new ArrayList<>();
                                    List<String> strings = new ArrayList();
                                    try {
                                        for (LinkedTreeMap linkedTreeMap : entry.getValue()) {
                                            strings.add((String) linkedTreeMap.get("id"));
                                        }
                                        for (LinkedTreeMap linkedTreeMap : entry.getValue()) { //航线是否在航线表
                                            list.add((Qnracess) StrUtils.jsonTobean(StrUtils.beanTojson(linkedTreeMap), Qnracess.class));//在航线表中 则更新
                                        }
                                        lists.addAll(list);
                                    } catch (ClassCastException e) {
                                    }
                                    redisService2.set(entry.getKey(), StrUtils.beanTojson(strings));

                                } else {
                                    List<String> lst = (List) StrUtils.jsonTobean(string, List.class);
                                    //获取新的航班
                                    List<String> strings = new ArrayList();
                                    try {
                                        for (LinkedTreeMap linkedTreeMap : entry.getValue()) {
                                            strings.add((String) linkedTreeMap.get("id"));
                                        }
                                    } catch (ClassCastException e) {
                                        e.printStackTrace();
                                    }
                                    // 去重复并集 将新的添加到航线表
                                    strings.removeAll(lst);
                                    lst.addAll(strings);
                                    //保存最新最多的航线数据
                                    redisService2.set(entry.getKey(), StrUtils.beanTojson(lst));
                                    List<Qnracess> list = new ArrayList<>();
                                    outterLoop:
                                    for (String s : lst) { //循环新航线表数据
                                        for (LinkedTreeMap linkedTreeMap : entry.getValue()) { //航线是否在航线表 如果在 直接加入待更新数据
                                            if (s.equals(linkedTreeMap.get("id"))) {
                                                list.add((Qnracess) StrUtils.jsonTobean(StrUtils.beanTojson(linkedTreeMap), Qnracess.class));//在航线表中 则更新
                                                continue outterLoop; //有就跳出当次循环
                                            }
                                        }
                                        LinkedTreeMap map1 = null;
                                        try {//如果不在 说明这个数据已经抓不到了 去redis取旧数据 并重置为0
                                            map1 = (LinkedTreeMap) StrUtils.jsonTobean(redisService.get(s), LinkedTreeMap.class);
                                            map1.put("lasttime", fmt.format(LocalDateTime.now()));
                                            map1.put("seatsForSale", "0");
                                            map1.put("seatsForJinji", "0");
                                            list.add((Qnracess) StrUtils.jsonTobean(StrUtils.beanTojson(map1), Qnracess.class));//在航线表中 则更新
                                        } catch (Exception e) {//如果还是不在 说明这个数据以前也没抓到 那就创建一个空的数据去存
                                        }
                                    }
                                    lists.addAll(list);
                                }
                            }
                            if (lists.size() > 0) {
                                for (Qnracess list : lists) {
                                    System.err.println(list.toString());
                                    String string = redisService.get(list.getId());
                                    //插回Redis
                                    redisService.set(list.getId(), StrUtils.beanTojson(list));
                                    redisService.expireByDay(list.getId(), dayDiff(list.getDate(), new SimpleDateFormat("yyyy-MM-dd").format(Calendar.getInstance().getTime()), "yyyy-MM-dd"));
                                    Qnracess l = list;
                                    Qnracess q = new Qnracess();
                                    if (null!=string && !string.equals("")){
                                        q = (Qnracess) StrUtils.jsonTobean(string, Qnracess.class);
                                    }
                                    q.setLasttime("");
                                    String s1 = MD5Utils.MD5Encode(StrUtils.beanTojson(q),"UTF-8");
                                    l.setLasttime("");
                                    String s2 = MD5Utils.MD5Encode(StrUtils.beanTojson(l),"UTF-8");
                                    if (!s1.equals(s2)){
                                        qnracessRepositoryService.save(list);
                                    }

                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }
                }
            }.start();
        }
    }

    /**
     * @param date1  字符串日期1
     * @param date2  字符串日期2
     * @param format 日期格式化方式  format="yyyy-MM-dd"
     * @return
     * @descript:计算两个字符串日期相差的天数
     */
    public static long dayDiff(String date1, String date2, String format) {
        SimpleDateFormat formater = new SimpleDateFormat(format);
        long diff = 0l;
        try {
            long d1 = formater.parse(date1).getTime();
            long d2 = formater.parse(date2).getTime();
            //diff=(Math.abs(d1-d2) / (1000 * 60 * 60 * 24));
            diff = (d1 - d2) / (1000 * 60 * 60 * 24);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return diff;
    }
}

